//
//  CZHomeViewController.m
//  小和微博
//
//  Created by 董晓合 on 15/2/15.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZHomeViewController.h"
#import "CZTool.h"
#import "UIBarButtonItem+Extension.h"
#import "CZScanViewController.h"
#import "CZTitleButton.h"
#import "CZTextTableViewController.h"
#import "CZPopMenuView.h"
#import "CZPhoto.h"
#import "CZUser.h"
#import "CZStatus.h"
#import "CZTableFooterView.h"

@interface CZHomeViewController ()

//@property (nonatomic, weak) CZDefaultCenterView *defaultCenterView;
@property (nonatomic, strong) NSMutableArray *statuses;

@end

@implementation CZHomeViewController


- (void)viewDidLoad {
 // 1.初始化导航条
    [self setupNav];
    
    // 2.初始化默认界面
    if (self.defaultCenterView != nil) {
        self.defaultCenterView.iconImageName = @"visitordiscover_feed_image_house";
        self.defaultCenterView.info = @"当你关注一些人以后，他们发布的最新消息会显示在这里";
    } else {
//    获取用户信息
        [self setupUserInfo];
        
        // 3.添加下拉刷新
        [self setupRefresh];
    }

}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    //    开始旋转
    if (self.defaultCenterView != nil) {
        
        [self.defaultCenterView startRotate];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    //  停止旋转
    [super viewWillDisappear:animated];
    if (self.defaultCenterView != nil) {
        
        [self.defaultCenterView stopRotate];
        
    }
}

#pragma mark - 初始化方法
- (void)setupUserInfo {

//  1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    2.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    取出授权模型
    CZAccount *account = [CZAccount accountFromSandbox];
    parameters[@"access_token"] = account.access_token;
    parameters[@"uid"] = account.uid;
//    3.发送请求
    NSString *string = @"https://api.weibo.com/2/users/show.json";
    [manager GET:string parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
//     取出得到的用户头像
        NSString *iconUrlString = responseObject[@"profile_image_url"];
//      判断获取的头像是否和储存的一致
        if ([account.profile_image_url isEqualToString:iconUrlString]) {
            return;
        }
//        如果不一致 更新头像
        account.profile_image_url = iconUrlString;
        [account save];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogDebug(@"%@",error);
    }];
    
}

- (void)setupNav {

    // 1.初始化导航条
    //    创建左侧和右侧按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" higImage:@"navigationbar_friendsearch_highlighted" target:self  action:@selector(friendsearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_pop" higImage:@"navigationbar_pop_highlighted" target:self action:@selector(scan)];
    
    //    标题
    CZTitleButton *titleBtn = [[CZTitleButton alloc]init];
    [titleBtn setTitle:@"首页" forState:UIControlStateNormal];
    //    设置默认状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    // 设置选中状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    
    [titleBtn sizeToFit];
    
    //    监听按钮点击时间
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleBtn;
}

#pragma mark - 加载微博数据
/**
 *  加载微博数据
 */
- (void)loadNewStatuses:(UIRefreshControl *)refreshControl
{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [CZAccount accountFromSandbox].access_token;
    // 取出数组中第一个元素的ID
    NSString *firstStatusIdstr = [[self.statuses firstObject] idstr];
    if (firstStatusIdstr != nil) {
        parameters[@"since_id"] = firstStatusIdstr;
    }
    
    // 3.发送请求
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 1.存储获取到得微博数据
        // 获取字典数组
        NSArray *newStatus = responseObject[@"statuses"];
        // 将字典数组转换为模型数据
        NSArray *models = [CZStatus objectArrayWithKeyValuesArray:newStatus];
        //        [self.statuses addObjectsFromArray:models];
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        
        // 2.刷新表格
        [self.tableView reloadData];
        
        // 3.关闭刷新控件
        [refreshControl endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogDebug(@"%@", error);
        // 3.关闭刷新控件
        [refreshControl endRefreshing];
    }];
}
/**
 *  添加刷新
 */
- (void)setupRefresh
{
    // 1.创建刷新控件
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    // 3.监听刷新事件
    [refreshControl addTarget:self action:@selector(loadNewStatuses:) forControlEvents:UIControlEventValueChanged];
    // 2.将刷新控件添加到tableview上
    [self.tableView addSubview:refreshControl];
    
    // 4.主动显示菊花
    [refreshControl beginRefreshing];
    
    // 5.主动调用加载数据方法
    [self loadNewStatuses:refreshControl];
    
//    6.添加上拉加载更多
    CZTableFooterView *tableFooterView = [CZTableFooterView tableFooterView];
    tableFooterView.height = 44;
    self.tableView.tableFooterView = tableFooterView;
    self.tableView.tableFooterView.hidden = YES;
    
}

- (void)loadMoreStatuses {

    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [CZAccount accountFromSandbox].access_token;
    // 取出数组中第一个元素的ID
    NSString *lastStatusIdstr = [[self.statuses lastObject] idstr];
    if (lastStatusIdstr != nil) {
#warning 微博ID较长 int容易溢出 要用longlongValue
        parameters[@"max_id"] = @([lastStatusIdstr longLongValue] - 1);
    }
    
    // 3.发送请求
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 1.存储获取到得微博数据
        // 获取字典数组
        NSArray *newStatus = responseObject[@"statuses"];
        // 将字典数组转换为模型数据
        NSArray *models = [CZStatus objectArrayWithKeyValuesArray:newStatus];
        //        [self.statuses addObjectsFromArray:models];
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        
        // 2.刷新表格
        [self.tableView reloadData];
        
        // 3.关闭刷新控件
        self.tableView.tableFooterView.hidden = YES;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogDebug(@"%@", error);
        // 3.关闭刷新控件
           self.tableView.tableFooterView.hidden = YES;
    }];


}


#pragma mark - 内部控制方法
- (void)titleBtnClick:(CZTitleButton *) titleBtn {

//  切换按钮点击状态
    titleBtn.selected = !titleBtn.selected;
    
    //UITableView *tb = [[UITableView alloc] init];
    CZTextTableViewController *textVc = [[CZTextTableViewController alloc] init];
    textVc.view.size = CGSizeMake(150, 200);
    
    [CZPopMenuView popFrom:titleBtn contentVc:textVc dismiss:^{
    //  切换按钮点击状态
    titleBtn.selected = !titleBtn.selected;
        
    }];

   // [self.navigationController.view addSubview:menuView];

}

- (void)friendsearch
{
    DDActionLog;
}

- (void)scan
{
   // DDActionLog;
//    弹出二维码界面
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"CZScanViewController" bundle:nil];
    CZScanViewController *scanVc = [sb instantiateInitialViewController];
    [self presentViewController:scanVc animated:YES completion:nil];
    
                        
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
    }
    
    // 2.设置数据
    // 2.1取出对应行的微博模型
    CZStatus *status =  self.statuses[indexPath.row];
    // 2.2从对应行的微博模型中取出对应的用户模型
    CZUser *user = status.user;
    // 2.3设置昵称
    cell.textLabel.text = user.name;
    // 2.4设置微博内容
    cell.detailTextLabel.text = status.text;
    // 2.5设置用户头像
    NSURL *iconUrlString = [NSURL URLWithString:user.profile_image_url];
    [cell.imageView sd_setImageWithURL:iconUrlString placeholderImage:[UIImage imageNamed:@"avatar_default_big"]];
    
    // 3.返回cell
    return cell;
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

//   判断是否需要加载更多
    if (self.statuses.count == 0 ||
        self.tableView.tableFooterView.hidden == NO) {
        return;
    }
  // 如果当前的偏移位等于 contentSize.height + contentInset.bottom - scrollView.height; 那么就需要加载更多数据
    CGFloat offsetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
    if (scrollView.contentOffset.y >= offsetY) {
        
        [self loadMoreStatuses];
    }
}

#pragma mark -懒加载
- (NSMutableArray *)statuses
{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

@end
